package com.gitee.webdav.monitor;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.http.ContentType;
import cn.hutool.json.JSONUtil;
import com.gitee.webdav.HomeStarter;
import com.gitee.webdav.kernel.MethodEnum;
import com.gitee.webdav.kernel.Remark;
import com.gitee.webdav.kernel.ResourceReadonlyHandler;
import org.smartboot.http.common.enums.HttpMethodEnum;
import org.smartboot.http.common.enums.HttpStatus;
import org.smartboot.http.server.HttpRequest;
import org.smartboot.http.server.HttpResponse;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author hongda.li@hand-china.com
 */
public class MonitorHandler extends ResourceReadonlyHandler {

    @Remark("内置监控页面路径")
    private static final String INDEX_HTML = "index.html";

    @Override
    public void handle(HttpRequest request, HttpResponse response) throws Throwable {
        String method = request.getMethod();
        if (HttpMethodEnum.GET.getMethod().equals(method)) {
            this.returnHtml(response);
        }
        if (HttpMethodEnum.POST.getMethod().equals(method)) {
            this.returnJson(response);
        }
        response.setHttpStatus(HttpStatus.METHOD_NOT_ALLOWED);
    }

    private void returnJson(HttpResponse response) throws IOException {
        response.setHttpStatus(HttpStatus.OK);
        writeContentType(response, ContentType.JSON.getValue());
        response.write(CharSequenceUtil.bytes(JSONUtil.toJsonStr(MonitorInfo.snapshot()), StandardCharsets.UTF_8));
    }

    private void returnHtml(HttpResponse response) {
        response.setHttpStatus(HttpStatus.OK);
        writeContentType(response, ContentType.TEXT_HTML.getValue());
        IoUtil.copy(ResourceUtil.getStreamSafe(INDEX_HTML), response.getOutputStream(), HomeStarter.getWriteBufferSize());
    }

    @Override
    protected MethodEnum method() {
        throw new UnsupportedOperationException();
    }
}
